package com.king.service;

import com.google.gson.JsonObject;
import com.king.bean.AccessToken;
import com.king.config.GlobalConst;
import com.king.utils.CommonUtils;

public class WxTokenService {

    private static final String ACCESS_TOKEN_URL = GlobalConst.getConfig("MP_ACCESS_TOKEN_URL");
    private static final String APPID = GlobalConst.getConfig("MP_APPID");
    private static final String APPSECRET = GlobalConst.getConfig("MP_APPSECRET");

    //获取AccessToken
    private static AccessToken token;

    /**
     * 获取access_token
     *
     * @return
     */
    public static String getAccessToken() {
        if (token == null || token.isExpired()) {
            getToken();
            System.out.println("获取了新Token: "+ token.getAccessToken());
        }

        return token.getAccessToken();
    }

    /**
     * 获取微信接口访问Token
     */
    private static void getToken() {
        String url = ACCESS_TOKEN_URL.replace("APPID", APPID).replace("APPSECRET", APPSECRET);
        String result = CommonUtils.get(url);

        JsonObject jsonObject = GlobalConst.gson.fromJson(result, JsonObject.class);
        String accessToken = jsonObject.get("access_token").getAsString();
        String expiresIn = jsonObject.get("expires_in").getAsString();

        token = new AccessToken(accessToken, expiresIn);
    }
}
